package com.stars.easyms.base.boot;

import com.stars.easyms.base.util.ApplicationContextHolder;
import com.stars.easyms.base.util.SpringBootUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.lang.NonNull;

/**
 * <p>className: EasyMsApplicationContextInitializer</p>
 * <p>description: EasyMs基础ApplicationContextHolder类进行加载</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-07-10 10:12
 */
@Slf4j
public class EasyMsApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {

    /**
     * 使用静态的，第一次注入就不再重新初始化
     */
    private static Class<?> applicationClass;

    /**
     * 用于springboot模式启动时设置全局保存applicationContext
     *
     * @param applicationContext applicationContext
     */
    @Override
    public void initialize(@NonNull ConfigurableApplicationContext applicationContext) {
        ApplicationContextHolder.setApplicationContext(applicationContext);
        // 获取当前执行的类，此处获取的是main方法的实现类
        if (EasyMsApplicationContextInitializer.applicationClass == null) {
            EasyMsApplicationContextInitializer.applicationClass = deduceMainApplicationClass();
            if (EasyMsApplicationContextInitializer.applicationClass != null) {
                SpringBootUtil.setSpringApplicationPackageName(EasyMsApplicationContextInitializer.applicationClass.getPackage().getName());
            }
        }
    }

    /**
     * springboot模式下ApplicationContextInitializer的顺序
     */
    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }

    private Class<?> deduceMainApplicationClass() {
        try {
            StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                if ("main".equals(stackTraceElement.getMethodName())) {
                    return Class.forName(stackTraceElement.getClassName());
                }
            }
        } catch (ClassNotFoundException ex) {
            // ignore
        }
        String applicationClassName = System.getProperty("sun.java.command");
        if (StringUtils.isNotBlank(applicationClassName)) {
            try {
                applicationClass = ClassUtils.getClass(applicationClassName);
            } catch (ClassNotFoundException e) {
                log.error("Class {} not found", applicationClassName);
                System.exit(1);
            }
        }
        return null;
    }
}